import { createContext, useContext, useState, ReactNode } from 'react';
import en from './translations/en';
import es from './translations/es';
import fr from './translations/fr';
import de from './translations/de';
import zh from './translations/zh';
import ja from './translations/ja';

// Supported languages
export const SUPPORTED_LANGUAGES = {
  en: 'English',
  es: 'Español',
  fr: 'Français',
  de: 'Deutsch',
  zh: '中文',
  ja: '日本語'
} as const;

export type Language = keyof typeof SUPPORTED_LANGUAGES;

// Translation interface
export interface Translations {
  // Header and Navigation
  header: {
    title: string;
    subtitle: string;
  };
  
  // Navigation tabs
  navigation: {
    instances: string;
    performance: string;
    slowQueries: string;
    storage: string;
  };

  // Dashboard stats
  stats: {
    runningInstances: string;
    totalConnections: string;
    avgCpuUsage: string;
    totalStorage: string;
  };

  // Database instances
  instances: {
    title: string;
    createNew: string;
    noInstances: string;
    getStarted: string;
    status: {
      running: string;
      stopped: string;
      pending: string;
      maintenance: string;
    };
    actions: {
      start: string;
      stop: string;
      delete: string;
      viewDetails: string;
    };
    details: {
      engine: string;
      version: string;
      region: string;
      instanceType: string;
      storage: string;
      connections: string;
      cpu: string;
      memory: string;
      createdAt: string;
    };
  };

  // Create database dialog
  createDatabase: {
    title: string;
    description: string;
    form: {
      name: string;
      namePlaceholder: string;
      engine: string;
      enginePlaceholder: string;
      version: string;
      versionPlaceholder: string;
      instanceType: string;
      instanceTypePlaceholder: string;
      region: string;
      regionPlaceholder: string;
      storage: string;
    };
    buttons: {
      cancel: string;
      create: string;
    };
  };

  // Performance monitoring
  performance: {
    title: string;
    selectDatabase: string;
    chooseDatabase: string;
    selectInstance: string;
    selectInstanceDescription: string;
    noRunningInstances: string;
    noRunningDescription: string;
    metrics: {
      cpuUsage: string;
      memoryUsage: string;
      activeConnections: string;
      storageUsed: string;
      status: {
        good: string;
        warning: string;
        critical: string;
      };
      charts: {
        cpu24h: string;
        memory24h: string;
        connections24h: string;
        iops24h: string;
      };
    };
    queryPerformance: {
      title: string;
      queryCount: string;
      avgResponse: string;
      avgQueryTime: string;
      networkIO: string;
      activeAlerts: string;
    };
  };

  // Slow queries
  slowQueries: {
    title: string;
    selectDatabase: string;
    chooseDatabase: string;
    table: {
      query: string;
      duration: string;
      database: string;
      timestamp: string;
      impact: string;
      actions: string;
    };
    actions: {
      optimize: string;
      explain: string;
      kill: string;
    };
    impact: {
      high: string;
      medium: string;
      low: string;
    };
  };

  // Storage monitoring
  storage: {
    title: string;
    totalStorage: string;
    usedStorage: string;
    available: string;
    usagePercent: string;
    high: string;
    normal: string;
    usageOverview: string;
    currentUsage: string;
    criticallyHigh: string;
    significantlyHigh: string;
    growthTrend: string;
    sizeDistribution: string;
    largestTables: string;
    totalCapacity: string;
    size: string;
    overview: {
      title: string;
      totalAllocated: string;
      totalUsed: string;
      freeSpace: string;
      utilizationRate: string;
    };
    byDatabase: {
      title: string;
      database: string;
      allocated: string;
      used: string;
      free: string;
      utilization: string;
    };
    growth: {
      title: string;
      projection: string;
    };
  };

  // Common
  common: {
    loading: string;
    error: string;
    success: string;
    warning: string;
    info: string;
    cancel: string;
    save: string;
    delete: string;
    confirm: string;
    close: string;
    refresh: string;
    language: string;
  };

  // Toast messages
  messages: {
    databaseCreated: string;
    databaseStarted: string;
    databaseStopped: string;
    databaseDeleted: string;
    viewingDetails: string;
    databaseRunning: string;
  };

  // Authentication
  auth: {
    login: {
      title: string;
      description: string;
      signIn: string;
      loggingIn: string;
      demoCredentials: string;
      demoUsername: string;
      demoPassword: string;
    };
    form: {
      username: string;
      usernamePlaceholder: string;
      password: string;
      passwordPlaceholder: string;
    };
    menu: {
      profile: string;
      settings: string;
      logout: string;
    };
    validation: {
      required: string;
    };
    errors: {
      invalidCredentials: string;
      networkError: string;
      serverError: string;
    };
  };
}

interface I18nContextType {
  language: Language;
  setLanguage: (language: Language) => void;
  t: Translations;
}

const I18nContext = createContext<I18nContextType | undefined>(undefined);

export function useI18n() {
  const context = useContext(I18nContext);
  if (context === undefined) {
    throw new Error('useI18n must be used within an I18nProvider');
  }
  return context;
}

interface I18nProviderProps {
  children: ReactNode;
}

export function I18nProvider({ children }: I18nProviderProps) {
  // Get initial language from localStorage or default to English
  const getInitialLanguage = (): Language => {
    if (typeof window !== 'undefined') {
      const savedLanguage = localStorage.getItem('language') as Language;
      if (savedLanguage && savedLanguage in SUPPORTED_LANGUAGES) {
        return savedLanguage;
      }
      // Try to detect browser language
      const browserLanguage = navigator.language.split('-')[0] as Language;
      if (browserLanguage in SUPPORTED_LANGUAGES) {
        return browserLanguage;
      }
    }
    return 'en';
  };

  const [language, setLanguageState] = useState<Language>(getInitialLanguage);

  const setLanguage = (newLanguage: Language) => {
    setLanguageState(newLanguage);
    if (typeof window !== 'undefined') {
      localStorage.setItem('language', newLanguage);
    }
  };

  // Get translations based on language
  const getTranslations = (lang: Language): Translations => {
    switch (lang) {
      case 'es':
        return es;
      case 'fr':
        return fr;
      case 'de':
        return de;
      case 'zh':
        return zh;
      case 'ja':
        return ja;
      default:
        return en;
    }
  };

  const t = getTranslations(language);

  return (
    <I18nContext.Provider value={{ language, setLanguage, t }}>
      {children}
    </I18nContext.Provider>
  );
}